package com.example.android4_lx;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class BindService extends Service{
    private int count;
    private boolean quit;

    // 定义onBinder方法所返回的对象
    private MyBinder binder = new MyBinder();
    // 通过继承Binder来实现IBinder类
    public class MyBinder extends Binder {
        public int getCount(){
            // 获取Service的运行状态：count
            return count;
        }
    }


    // Service被创建时回调该方法。
    @Override
    public void onCreate(){
        super.onCreate();
        Log.d("Service","is created");
        // 启动一条线程、动态地修改count状态值
        new Thread(){
            @Override
            public void run(){
                while (!quit){
                    try{
                        Thread.sleep(1000);
                    }
                    catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        }.start();
    }
    // 必须实现的onBind方法
    @Override
    public IBinder onBind(Intent intent) {
        Log.d("Service","is binded");
        return binder;
    }
    // Service被断开连接时回调该方法
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("Service","is unbinded");
        return true;
    }

    // Service被关闭之前回调。
    @Override
    public void onDestroy(){
        super.onDestroy();
        this.quit=true;
        //即使activity结束也不一定结束service,关闭activity也不一定会结束activity
        Log.d("Service","is destroyed");
    }


}
